package com.dzsw.simple.server.util;


import org.apache.commons.lang3.StringUtils;
import org.apache.tika.Tika;
import org.springframework.util.Assert;

import java.io.*;
import java.util.Optional;

public class FileUtil {

    public static String getFileBase64(byte[] bytes) {
        return Base64Util.encode(bytes);
    }

    public static String getFileBase64(String filePath) throws Exception {
        String ret = "";
        Optional<byte[]> optional = getFileBytes(filePath);
        if (optional.isPresent()) {
            ret = getFileBase64(optional.get());
        }
        return ret;
    }

    public static String getInputStreamBase64(InputStream inputStream) throws Exception {
        byte[] bytes = getInputStreamBytes(inputStream);
        if (bytes == null) {
            return "";
        } else {
            return getFileBase64(bytes);
        }
    }

    public static byte[] getInputStreamBytes(InputStream inputStream) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len = 0;
        while ((len = inputStream.read(buff)) > 0) {
            out.write(buff, 0, len);
        }
        return out.toByteArray();
    }

    public static Optional<byte[]> getFileBytes(String filePath) throws Exception {
        File file = new File(filePath);
        return getFileBytes(file);
    }

    public static Optional<byte[]> getFileBytes(File file) throws Exception {
        if (!file.exists()) {
            return Optional.empty();
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        return Optional.ofNullable(getInputStreamBytes(fileInputStream));
    }

    /**
     * get file content type, default application/octet-stream
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static String getContentType(InputStream inputStream) throws Exception {
        Assert.notNull(inputStream, "FileUtil.getContentType >> inputStream must not be null");
        String contentType = "application/octet-stream";
        Tika tika = new Tika();
        String tmp = tika.detect(inputStream);
        if (StringUtils.isNotEmpty(tmp)) {
            contentType = tmp;
        }
        return contentType;
    }

    /**
     * get file content type, default application/octet-stream
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String getContentType(File file) throws Exception {
        Assert.notNull(file, "FileUtil.getContentType >> file must not be null");
        String contentType = "application/octet-stream";
        Tika tika = new Tika();
        String tmp = tika.detect(file);
        if (StringUtils.isNotEmpty(tmp)) {
            contentType = tmp;
        }
        return contentType;
    }


    /**
     * save to local storage
     *
     * @param inputStream
     * @param fullName
     * @throws Exception
     */
    public static void saveToLocal(InputStream inputStream, String fullName) throws Exception {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fullName);
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) > 0) {
                fos.write(buff, 0, len);
            }
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }

    /**
     * byte array to hex string
     *
     * @param src
     * @return
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * get file head
     *
     * @param filePath file path
     * @return file head 28bit
     * @throws IOException
     */
    private static String getFileContent(String filePath) throws IOException {
        byte[] b = new byte[28];
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            inputStream.read(b, 0, 28);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw e;
                }
            }
        }
        return bytesToHexString(b);
    }
}
